#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import base64
import json
import Lib.Logger.log4py as logging
from mj_parser import common_errors
import sys
import traceback

class FordParserWeb:
    default_result = {
        "model":            '',
        "year":             '',
        "prod_date":        '',
        "air_conditioner":  '',   #空调系统
        "body_style":       '', #车身款式
        "fabric":           '', #T 内饰面料
        "paint":            '', #P 车身油漆
        "transmission":     '',
        "engine":           '',
        "axle_speed_ratio": '', #E 车桥降速比
        "region":           '', #W地区
        "vl":               '', # VL
        "version":          '',
        "drive":            '', #DR 驱动器
        "emission":         '', #EM 排放
        "inner_color":      '', #内部环境, 000
        "avs_data":         '',
        "raw_content":      ''
    }

    def __init__(self, root_dir='.'):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "FordParserWeb")

    def parse(self, file_name):
        b = common_errors.ERR_SUCCESS
        result_list = self.get_default_result()
        try:
            fobj = open(file_name, encoding='utf_8_sig')
            f_buff = fobj.read()
            catalog = json.loads(f_buff)
            vehicle = catalog['vehicle']

            result_list['model'] = catalog['label']
            result_list['year'] = vehicle['modelYear']
            result_list['prod_date'] = vehicle['buildDate']
            result_list['air_conditioner'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'AC')
            result_list['body_style'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'BS')
            result_list['fabric'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'T')
            result_list['paint'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'P')
            result_list['transmission'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'TR')
            result_list['engine'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'EN')
            result_list['axle_speed_ratio'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'E')
            result_list['region'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'W')
            result_list['vl'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'VL')
            result_list['version'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'VS')
            result_list['drive'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'DR')
            result_list['emission'] = self.get_vehicle_info(vehicle['interpretationAVSData'], 'EM')
            result_list['inner_color'] = self.get_vehicle_info(vehicle['interpretationAVSData'], '000')

            result_list['raw_content'] = base64.b64encode(f_buff.encode('utf-8')).decode('utf-8')
            result_list['avs_data'] = self.get_minor_info(vehicle['interpretationAVSData'])

        except Exception as ex:
            try:
                b = common_errors.ERR_UNKNOWN
                exc_info = sys.exc_info()
                self.logger.error(ex)
            finally:
                traceback.print_exception(*exc_info)
                del exc_info
        return b, result_list

    def get_vehicle_info(self, vehicle_list, component):
        for vehicle_item in vehicle_list:
            if vehicle_item["type"] == component:
                return vehicle_item["data"]
        return None

    def get_minor_info(self,vehicle_list):
        result_list = []
        #major_list = ['AC', 'BS', 'T', 'P', 'TR', 'EN', 'E', 'W', 'VL', 'VS', 'DR', 'EM', '000']
        for vehicle_item in vehicle_list:
            #if vehicle_item["type"] not in major_list:
            result_list.append(vehicle_item["data"])
        return ' '.join(result_list)

    def get_default_result(self):
        return FordParserWeb.default_result.copy()

if __name__ == '__main__':
    parser = FordParserWeb()
    # .\\data\\SALVA2BG2DH800209.json
    code, res = parser.parse('..\\mj_source\\data\\LVSHJCAC7HE234695.json')
    print(code)
    print(res)